import { makeAutoObservable } from "mobx";
import type { TodoItem, FilterType } from "./index.d";
export class TodosStore {
  todos: TodoItem[] = [];
  filter: FilterType = "All";

  constructor() {
    makeAutoObservable(this);
  }

  // 添加待办事项
  addTodo = (text: string) => {
    if (text.trim()) {
      const newTodo: TodoItem = {
        id: Date.now().toString(),
        text: text.trim(),
        completed: false,
        createdAt: new Date(),
      };
      this.todos.push(newTodo);
    }
  };

  // 删除待办事项
  removeTodo = (id: string) => {
    this.todos = this.todos.filter((todo) => todo.id !== id);
  };

  // 切换完成状态
  toggleTodo = (id: string) => {
    const todo = this.todos.find((todo) => todo.id === id);
    if (todo) {
      todo.completed = !todo.completed;
    }
  };

  // 设置筛选条件
  setFilter = (filter: FilterType) => {
    this.filter = filter;
  };

  // 清除所有已完成
  clearCompleted = () => {
    this.todos = this.todos.filter((todo) => !todo.completed);
  };

  // 计算属性：获取筛选后的待办事项
  get filteredTodos(): TodoItem[] {
    switch (this.filter) {
      case "Active":
        return this.todos.filter((todo) => !todo.completed);
      case "Completed":
        return this.todos.filter((todo) => todo.completed);
      default:
        return this.todos;
    }
  }

  // 计算属性：剩余未完成数量
  get activeTodoCount(): number {
    return this.todos.filter((todo) => !todo.completed).length;
  }

  // 计算属性：是否有已完成的项目
  get hasCompleted(): boolean {
    return this.todos.some((todo) => todo.completed);
  }

  // 计算属性：是否所有项目都完成
  get allCompleted(): boolean {
    return this.todos.length > 0 && this.todos.every((todo) => todo.completed);
  }

  // 切换所有项目的完成状态
  toggleAll = () => {
    const allCompleted = this.allCompleted;
    this.todos.forEach((todo) => {
      todo.completed = !allCompleted;
    });
  };
}

export const todosStore = new TodosStore();
